package com.mind.api;

import com.mind.api.webservice.ShareCallbackResponse;
import com.mind.common.utils.uuid.UUID;
import com.mind.system.domain.vo.ShareCallBackVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Log4j2
public class WebServiceClient {

    private final RestTemplate restTemplate;

    public WebServiceClient() {
        this.restTemplate = new RestTemplate();
    }

    public String callWebService(String url, String requestXml) {
        log.info("回调请求：{}", requestXml);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/xml; charset=utf-8");
        HttpEntity<String> entity = new HttpEntity<>(requestXml, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String call(String url, String body, Map<String, Object> header) {
        HttpHeaders headers = new HttpHeaders();
        if(header != null){
            for (Map.Entry<String, Object> entry : header.entrySet()) {
                headers.add(entry.getKey(), entry.getValue().toString());
            }
        }
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(body, headers);

        try {
            log.info("url:{}, params:{}", url, body);
            if(header != null){
                log.info("header:{}", header);
            }
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    // todo 稽核结果回调实现
    public ShareCallbackResponse callWebService(String url, ShareCallBackVo callBackVo) throws JAXBException, Exception {
        String soapResponse = callWebService(url, getSOAPString(callBackVo));
        log.info("回调结果：{}", soapResponse);
        JAXBContext jaxbContext = JAXBContext.newInstance(ShareCallbackResponse.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        ShareCallbackResponse shareCallbackResponse = (ShareCallbackResponse) unmarshaller.unmarshal(new StringReader(soapResponse));
        log.info("回调结果：{}", shareCallbackResponse);
        if (shareCallbackResponse == null) {
            throw new Exception(String.format("回调失败, 响应结果：%s", soapResponse));
        }
        if (shareCallbackResponse.getBody() == null) {
            throw new Exception(String.format("回调失败, 响应结果：%s", soapResponse));
        }
        if (shareCallbackResponse.getBody().getGetSmartCheckReturnDataResponse() == null) {
            throw new Exception(String.format("回调失败, 响应结果：%s", soapResponse));
        }
        if (shareCallbackResponse.getBody().getGetSmartCheckReturnDataResponse().getCONTENT() == null) {
            throw new Exception(String.format("回调失败, 响应结果：%s", soapResponse));
        }
        if (shareCallbackResponse.getBody().getGetSmartCheckReturnDataResponse().getCONTENT().getOResult() == null) {
            throw new Exception(String.format("回调失败, 响应结果：%s", soapResponse));
        }
        if(!shareCallbackResponse.getBody().getGetSmartCheckReturnDataResponse().getCONTENT().getOResult().equals("0")) {
            throw new Exception(String.format("回调失败, 响应结果：%s", soapResponse));
        }
        return shareCallbackResponse;
    }


    private String getSOAPString(ShareCallBackVo callBackVo) {
        return String.format("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://ofbiz.apache.org/service/\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <ser:getSmartCheckReturnData>\n" +
                "         <Head>\n" +
                "            <biztransactionid>%s</biztransactionid>\n" +
                "            <account>1</account>\n" +
                "            <count>1</count>\n" +
                "            <password>1</password>\n" +
                "            <srvlevel>1</srvlevel>\n" +
                "            <taid>wjs</taid>\n" +
                "            <!--Optional:-->\n" +
                "            <auditComments>%s</auditComments>\n" +
                "            <auditUser>%s</auditUser>\n" +

                "            <!--Optional:-->\n" +
                "            <auditDate>%s</auditDate>\n" +
                "            <!--Optional:-->\n" +
                "            <auditResult>%s</auditResult>\n" +
                "            <!--Optional:-->\n" +
                "            <documentNum>%s</documentNum>\n" +
                "         </Head>\n" +
                "         <LIST/>\n" +
                "      </ser:getSmartCheckReturnData>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope> ", UUID.fastUUID(), callBackVo.getComments(), callBackVo.getAuditUser(), callBackVo.getDate(), callBackVo.getResult(), callBackVo.getTicketId());
    }


    public static void main(String[] args) {
        String text = "业务号用章米捷业务LB岛金海食品工业卤食品工308590194760宾阳通85955605882024.07.2462,724.902,100.0029.869点TG8U6031529/62783300对应订单号订单数量发贷总金政折算单价（MT）净重提单号PGI日期结算单S有";
        String regex = ".*(提单号.*结算单)|(结算单.*提单号).*"; // 要搜索的正则表达式

        // 编译正则表达式
        Pattern pattern = Pattern.compile(regex);

        // 创建 Matcher 对象
        Matcher matcher = pattern.matcher(text);

        // 搜索第一个匹配项
        if (matcher.find()) {
            // 获取并打印第一个匹配项
            System.out.println("找到第一个匹配项：" + matcher.group());
        } else {
            System.out.println("没有找到匹配项。");
        }
    }

}
